<template>
  <Chart ref="chartRef" class="chart" v-bind="$attrs" autoresize :option="options" />
</template>

<script lang="ts" setup>
import { ref, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { cloneDeep } from 'lodash-es'
import Chart from 'vue-echarts'
import type { EChartsOption } from 'echarts'

const props = withDefaults(
  defineProps<{
    clear?: boolean
    resize?: boolean
    option: EChartsOption
    removeTooltip?: boolean
  }>(),
  { clear: true, resize: true }
)

const emit = defineEmits<{
  (e: 'ready'): void
}>()

const chartRef = ref()

const options = ref<EChartsOption>()

onMounted(() => {
  props.removeTooltip && document.body.addEventListener('click', removeTooltips)
})

onUnmounted(() => {
  props.removeTooltip && document.body.removeEventListener('click', removeTooltips)
})

function removeTooltips(e: MouseEvent) {
  if (chartRef.value && props.removeTooltip) {
    // console.log('removeTooltip', chartRef.value);
    const { left, top, width, height } = chartRef.value.$el.getBoundingClientRect()
    const x = e.clientX
    const y = e.clientY
    if (x < left || x > left + width || y < top || y > top + height) {
      // 隐藏tooltip
      chartRef.value.dispatchAction({
        type: 'hideTip'
      })
    }
  }
}

watch(
  () => props.option,
  () => {
    if (chartRef.value && props.clear) {
      chartRef.value.clear()
    }
    if (chartRef.value && props.resize) {
      chartRef.value.resize()
    }

    options.value = cloneDeep(props.option as EChartsOption)
    nextTick(() => {
      setTimeout(
        () => {
          emit('ready')
        },
        Number(options.value?.animationDuration) || 1000
      )
    })
  },
  { immediate: true, deep: true }
)

// watch(option, () => {
//   console.log('watch option', JSON.stringify(option.value));
// });

defineExpose({
  chartRef
})
</script>
